import java.lang.reflect.Array;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-04-09
 * Time: 20:27
 */
public class HashBuck {
    static class Node {
        public int key;
        public int value;
        public Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node[] array = new Node[10];
    public int usedSize;
    public static final double  LOAD_FACTOR = 0.75;
    //插入
    public void push(int key,int value) {
        //1.找到位置
        int index = key % array.length;
        //2.遍历该位置的链表
        Node cur = array[index];
        Node node = new Node(key,value);
        while(cur != null) {
            //更新value
            if(cur.key == key) {
                cur.value = value;
            }
            cur = cur.next;
        }
        //尾插法
        node.next = array[index];
        array[index] = node;
        usedSize++;
        //3.判断负载因子
        if(doLoadFactor() >= LOAD_FACTOR) {
            //重新哈希
            reHash();
        }
    }
    private double doLoadFactor() {
        return usedSize * 1.0 / array.length;
    }
    private void reHash() {
        //1.将数组扩容
        Node[] newArray = new Node[array.length*2];
        //2.遍历数组每一个位置
        for (int i = 0; i < array.length; i++) {
            //2.1遍历每一个位置的链表
            Node cur = array[i];
            while(cur != null) {
                //重新确定位置
                int index = cur.key % newArray.length;
                //记录下一个结点
                Node curNext = cur.next;
                cur.next = newArray[index];
               newArray[index] = cur;
               cur = curNext;
            }
        }
        //将数据放回原数组中
        array = newArray;
    }

    public int get(int key) {
        //1.找到位置
        int index = key % array.length;
        //2.遍历该位置的链表
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }

}
